﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Data.SqlClient;

namespace ThiTracNghiem
{
    public partial class FormRestore : Form
    {
        public FormRestore()
        {
            InitializeComponent();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            if (txtFileLocation.Text.Equals(""))
            {
                bakFileChooserDialog.Filter = "Backup File(*.bak)|*.bak";
                bakFileChooserDialog.InitialDirectory = Application.StartupPath;
            }
            else
            {
                bakFileChooserDialog.Filter = "Backup File(*.bak)|*.bak";
                bakFileChooserDialog.InitialDirectory = Path.GetDirectoryName(txtFileLocation.Text.Trim());
            }

            if (bakFileChooserDialog.ShowDialog() == DialogResult.OK)
            {
                txtFileLocation.Text = bakFileChooserDialog.FileName;
                using (SqlConnection con = new SqlConnection(Program.ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("SP_GET_BACKUP", con))
                    {

                        try
                        {
                            con.Open();
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.Add("@TYPE", SqlDbType.Int).Value = 1;
                            cmd.Parameters.Add("@DEVICE", SqlDbType.NVarChar).Value = txtFileLocation.Text;
                            DataTable myTable = new DataTable();
                            myTable.Load(cmd.ExecuteReader());
                            dgvContents.DataSource = myTable;
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show("Lỗi đã xảy ra.\nChi tiết: " + ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
        }

        private void rbDevice_CheckedChanged(object sender, EventArgs e)
        {
            dgvContents.DataSource = null;
            if (rbDevice.Checked)
            {
                cbDevice.Enabled = true;
                btnBrowse.Enabled = false;
                cbDevice_SelectedIndexChanged(null, null);
            }
            else
            {
                cbDevice.Enabled = false;
                btnBrowse.Enabled = true;
                if (!txtFileLocation.Text.Equals(""))
                {
                    using (SqlConnection con = new SqlConnection(Program.ConnectionString))
                    {
                        using (SqlCommand cmd = new SqlCommand("SP_GET_BACKUP", con))
                        {
                            try
                            {
                                con.Open();
                                cmd.CommandType = CommandType.StoredProcedure;
                                cmd.Parameters.Add("@TYPE", SqlDbType.Int).Value = 1;
                                cmd.Parameters.Add("@DEVICE", SqlDbType.NVarChar).Value = txtFileLocation.Text;
                                DataTable myTable = new DataTable();
                                myTable.Load(cmd.ExecuteReader());
                                dgvContents.DataSource = myTable;
                            }
                            catch (System.Exception ex)
                            {
                                MessageBox.Show("Lỗi đã xảy ra.\nChi tiết: " + ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                }
            }
        }

        private void FormRestore_Load(object sender, EventArgs e)
        {
            using (SqlConnection con = new SqlConnection(Program.ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM sys.backup_devices", con))
                {
                    try
                    {
                        con.Open();
                        SqlDataReader reader = cmd.ExecuteReader();

                        while (reader.Read())
                        {
                            cbDevice.Items.Add(reader[0].ToString());
                        }
                    }
                    catch (System.Exception ex)
                    {
                        MessageBox.Show("Lỗi đã xảy ra.\nChi tiết: " + ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                }
            }
        }

        private void cbDevice_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbDevice.SelectedIndex >= 0)
            {
                using (SqlConnection con = new SqlConnection(Program.ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand("SP_GET_BACKUP", con))
                    {
                        try
                        {
                            con.Open();
                            cmd.CommandType = CommandType.StoredProcedure;
                            cmd.Parameters.Add("@TYPE", SqlDbType.Int).Value = 2;
                            cmd.Parameters.Add("@DEVICE", SqlDbType.NVarChar).Value = cbDevice.SelectedItem;
                            DataTable myTable = new DataTable();
                            myTable.Load(cmd.ExecuteReader());
                            dgvContents.DataSource = myTable;
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show("Lỗi đã xảy ra.\nChi tiết: " + ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (dgvContents.SelectedRows.Count > 0)
            {
                DataGridViewRow row = dgvContents.SelectedRows[0];
                int file = 0;
                int type = 0;
                String src = "";

                String tmp = row.Cells[1].Value.ToString();
                if (rbFile.Checked)
                {
                    src = txtFileLocation.Text;
                    if (tmp.Equals("Full"))
                    {
                        type = 0;
                    }
                    else if (tmp.Equals("Transaction Log"))
                    {
                        type = 2;
                    }
                    else
                    {
                        type = 1;
                    }
                }
                else
                {
                    src = cbDevice.SelectedItem.ToString();
                    if (tmp.Equals("Full"))
                    {
                        type = 3;
                    }
                    else if (tmp.Equals("Transaction Log"))
                    {
                        type = 5;
                    }
                    else
                    {
                        type = 4;
                    }
                }

                file = int.Parse(row.Cells[2].Value.ToString());

                using (SqlConnection con = new SqlConnection(Program.ConnectionString))
                {
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        try
                        {
                            cmd.Connection = con;
                            cmd.CommandText = "SELECT DB_NAME()";
                            con.Open();
                            String dbName = (String)cmd.ExecuteScalar();

                            String cmdText = "use master "
                                + "declare @execSql varchar(1000), "
                                + "@dbName varchar(100) "
                                + "set @dbName = '" + dbName + "' "
                                + "set @execSql = ''; "
                                + "select  @execSql = @execSql + 'kill ' + convert(char(10), spid) + ' ' "
                                + "from sysprocesses "
                                + "where db_name(dbid) = @dbName and  dbid <> 0 and spid <> @@spid "
                                + "exec(@execSql);\n "
                                + " use master ALTER DATABASE [" + dbName + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE \n";

                            if (type == 0 || type == 1)
                            {
                                cmdText += " RESTORE DATABASE " + dbName + "  FROM DISK ='" + txtFileLocation.Text + "' WITH REPLACE, FILE =" + file;
                            }
                            else if (type == 2)
                            {
                                cmdText += " RESTORE LOG " + dbName + " FROM DISK ='" + txtFileLocation.Text + "' WITH REPLACE, FILE =" + file;
                            }
                            else if (type == 3 || type == 4)
                            {
                                cmdText += " RESTORE DATABASE " + dbName + " FROM [" + cbDevice.SelectedItem + "] WITH REPLACE, FILE =" + file;
                            }
                            else if (type == 5)
                            {
                                cmdText += " RESTORE LOG " + dbName + " FROM [" + cbDevice.SelectedItem + "] WITH REPLACE, FILE =" + file;
                            }

                            cmdText += " \nALTER DATABASE [" + dbName + "] SET MULTI_USER WITH ROLLBACK IMMEDIATE";
                            cmd.CommandText = cmdText;
                            cmd.ExecuteNonQuery();

                            for (int i = progress.Minimum; i < progress.Maximum; i++)
                            {
                                progress.Value += 1;
                            }

                            MessageBox.Show("Restore database thành công", "Thành công", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        catch (System.Exception ex)
                        {
                            MessageBox.Show("Lỗi đã xảy ra.\nChi tiết: " + ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
        }

        private void txtFileLocation_TextChanged(object sender, EventArgs e)
        {
            txtFileLocation.SelectAll();
        }

        private void txtFileLocation_Click(object sender, EventArgs e)
        {
            txtFileLocation.SelectAll();
        }
    }
}
